<template>
  <div class="user-management-container">
    <!-- 主内容区域 -->
    <main class="content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>用户管理</h1>
        <el-button type="primary" @click="showAddUserDialog">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-number">{{ totalUsers }}</div>
              <div class="stat-label">用户总数</div>
              <div class="stat-icon total"><el-icon><UserFilled /></el-icon></div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-number">{{ activeUsers }}</div>
              <div class="stat-label">活跃用户</div>
              <div class="stat-icon active"><el-icon><SuccessFilled /></el-icon></div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-number">{{ adminUsers }}</div>
              <div class="stat-label">管理员</div>
              <div class="stat-icon admin"><el-icon><Setting /></el-icon></div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-number">{{ todayLogins }}</div>
              <div class="stat-label">今日登录</div>
              <div class="stat-icon login"><el-icon><TrendCharts /></el-icon></div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索筛选区域 -->
      <div class="search-section">
        <el-card>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-input v-model="searchQuery" placeholder="搜索用户名/姓名/手机号" prefix-icon="Search" />
            </el-col>
            <el-col :span="6">
              <el-select v-model="roleFilter" placeholder="选择角色">
                <el-option label="全部角色" value="" />
                <el-option label="管理员" value="admin" />
                <el-option label="普通用户" value="user" />
                <el-option label="操作员" value="operator" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="statusFilter" placeholder="选择状态">
                <el-option label="全部状态" value="" />
                <el-option label="正常" value="active" />
                <el-option label="禁用" value="inactive" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 用户列表 -->
      <div class="user-list-section">
        <el-card>
          <el-table :data="paginatedUsers" style="width: 100%" height="500px">
            <el-table-column prop="id" label="用户ID" width="100" />
            <el-table-column prop="username" label="用户名" width="120" />
            <el-table-column prop="realName" label="姓名" width="120" />
            <el-table-column prop="phone" label="手机号" width="140" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="role" label="角色" width="100">
              <template #default="scope">
                <el-tag :type="getRoleType(scope.row.role)">
                  {{ getRoleText(scope.row.role) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                  {{ scope.row.status === 'active' ? '正常' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastLogin" label="最后登录" width="180" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button type="primary" link @click="showEditUserDialog(scope.row)">编辑</el-button>
                <el-button 
                  v-if="scope.row.status === 'active'" 
                  type="warning" 
                  link 
                  @click="toggleUserStatus(scope.row.id, 'inactive')"
                >
                  禁用
                </el-button>
                <el-button 
                  v-else 
                  type="success" 
                  link 
                  @click="toggleUserStatus(scope.row.id, 'active')"
                >
                  启用
                </el-button>
                <el-button type="danger" link @click="confirmDeleteUser(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredUsers.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </main>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
            <el-option label="操作员" value="operator" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEditMode">
          <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEditMode">
          <el-input v-model="formData.confirmPassword" type="password" placeholder="请确认密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
    >
      <p>确定要删除该用户吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteUser">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { 
  Plus, UserFilled, SuccessFilled, Setting, TrendCharts 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const users = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const isEditMode = ref(false)
const userForm = ref(null)
const selectedUserId = ref('')

// 表单数据
const formData = ref({
  username: '',
  realName: '',
  phone: '',
  email: '',
  role: 'user',
  status: 'active',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 统计数据计算
const totalUsers = computed(() => users.value.length)
const activeUsers = computed(() => users.value.filter(user => user.status === 'active').length)
const adminUsers = computed(() => users.value.filter(user => user.role === 'admin').length)
const todayLogins = computed(() => {
  const today = new Date().toDateString()
  return users.value.filter(user => new Date(user.lastLogin).toDateString() === today).length
})

// 筛选后的用户列表
const filteredUsers = computed(() => {
  let filtered = users.value
  
  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(user => 
      user.username.toLowerCase().includes(query) ||
      user.realName.toLowerCase().includes(query) ||
      user.phone.includes(query)
    )
  }
  
  // 角色筛选
  if (roleFilter.value) {
    filtered = filtered.filter(user => user.role === roleFilter.value)
  }
  
  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(user => user.status === statusFilter.value)
  }
  
  // 按创建时间倒序排序
  filtered.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
  
  return filtered
})

// 分页后的用户列表
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})

// 角色类型映射
const getRoleType = (role) => {
  const roleTypes = {
    'admin': 'danger',
    'user': '',
    'operator': 'warning'
  }
  return roleTypes[role] || ''
}

// 角色文本映射
const getRoleText = (role) => {
  const roleTexts = {
    'admin': '管理员',
    'user': '普通用户',
    'operator': '操作员'
  }
  return roleTexts[role] || role
}

// 初始化数据
onMounted(() => {
  initMockData()
})

// 初始化模拟数据
function initMockData() {
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  const lastWeek = new Date(today)
  lastWeek.setDate(lastWeek.getDate() - 7)
  
  users.value = [
    {
      id: '1001',
      username: 'admin',
      realName: '系统管理员',
      phone: '13812345678',
      email: 'admin@example.com',
      role: 'admin',
      status: 'active',
      lastLogin: today.toLocaleString('zh-CN'),
      createTime: '2024-01-01 09:00:00'
    },
    {
      id: '1002',
      username: 'zhangsan',
      realName: '张三',
      phone: '13987654321',
      email: 'zhangsan@example.com',
      role: 'user',
      status: 'active',
      lastLogin: today.toLocaleString('zh-CN'),
      createTime: '2024-01-02 10:00:00'
    },
    {
      id: '1003',
      username: 'lisi',
      realName: '李四',
      phone: '13756789012',
      email: 'lisi@example.com',
      role: 'operator',
      status: 'active',
      lastLogin: yesterday.toLocaleString('zh-CN'),
      createTime: '2024-01-03 11:00:00'
    },
    {
      id: '1004',
      username: 'wangwu',
      realName: '王五',
      phone: '13698765432',
      email: 'wangwu@example.com',
      role: 'user',
      status: 'inactive',
      lastLogin: lastWeek.toLocaleString('zh-CN'),
      createTime: '2024-01-04 12:00:00'
    },
    {
      id: '1005',
      username: 'zhaoliu',
      realName: '赵六',
      phone: '13589012345',
      email: 'zhaoliu@example.com',
      role: 'user',
      status: 'active',
      lastLogin: today.toLocaleString('zh-CN'),
      createTime: '2024-01-05 13:00:00'
    }
  ]
}

// 显示新增用户对话框
function showAddUserDialog() {
  dialogTitle.value = '新增用户'
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 显示编辑用户对话框
function showEditUserDialog(user) {
  dialogTitle.value = '编辑用户'
  isEditMode.value = true
  selectedUserId.value = user.id
  formData.value = { ...user }
  dialogVisible.value = true
}

// 重置表单
function resetForm() {
  formData.value = {
    username: '',
    realName: '',
    phone: '',
    email: '',
    role: 'user',
    status: 'active',
    password: '',
    confirmPassword: ''
  }
  if (userForm.value) {
    userForm.value.clearValidate()
  }
}

// 提交表单
function submitForm() {
  if (!userForm.value) return
  
  userForm.value.validate((valid) => {
    if (valid) {
      if (isEditMode.value) {
        // 更新用户信息
        const index = users.value.findIndex(user => user.id === selectedUserId.value)
        if (index !== -1) {
          users.value[index] = { ...users.value[index], ...formData.value }
          ElMessage.success('用户信息更新成功')
        }
      } else {
        // 新增用户
        const newUser = {
          ...formData.value,
          id: `100${users.value.length + 1}`,
          lastLogin: new Date().toLocaleString('zh-CN'),
          createTime: new Date().toLocaleString('zh-CN')
        }
        users.value.unshift(newUser)
        ElMessage.success('用户添加成功')
      }
      dialogVisible.value = false
    }
  })
}

// 切换用户状态
function toggleUserStatus(userId, status) {
  const user = users.value.find(user => user.id === userId)
  if (user) {
    const action = status === 'active' ? '启用' : '禁用'
    ElMessageBox.confirm(`确定要${action}该用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      user.status = status
      ElMessage.success(`用户已${action}`)
    }).catch(() => {
      ElMessage.info('已取消操作')
    })
  }
}

// 确认删除用户
function confirmDeleteUser(userId) {
  selectedUserId.value = userId
  deleteDialogVisible.value = true
}

// 删除用户
function deleteUser() {
  const index = users.value.findIndex(user => user.id === selectedUserId.value)
  if (index !== -1) {
    users.value.splice(index, 1)
    ElMessage.success('用户删除成功')
  }
  deleteDialogVisible.value = false
}

// 搜索处理
function handleSearch() {
  currentPage.value = 1
}

// 重置筛选条件
function resetFilters() {
  searchQuery.value = ''
  roleFilter.value = ''
  statusFilter.value = ''
  currentPage.value = 1
}

// 处理页码变化
function handleSizeChange(size) {
  pageSize.value = size
}

// 处理页面变化
function handleCurrentChange(current) {
  currentPage.value = current
}
</script>

<style scoped>
.user-management-container {
  width: 100%;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 36px;
  opacity: 0.2;
}

.stat-icon.total {
  color: #909399;
}

.stat-icon.active {
  color: #67c23a;
}

.stat-icon.admin {
  color: #f56c6c;
}

.stat-icon.login {
  color: #409eff;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 20px;
}

/* 用户列表样式 */
.user-list-section {
  margin-bottom: 20px;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>